package com.shawn.springboot.integeration.netty.client.initializer;

import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author zhangjian
 * @title: AbstractChannelInitializer
 * @projectName 12-springboot学习
 * @description: 通道初始化设置模板
 * @date 2021/4/2716:02
 */
public abstract class AbstractChannelInitializer extends ChannelInitializer<SocketChannel> {
    // 获取SSL处理器,子类可重写
    protected SslHandler getSslHandler(SocketChannel sc) {return null;}
    // 获取心跳检测处理器,子类可重写
    protected IdleStateHandler getIdleStateHandler(){return null;}
    // 获取自定义解码器,由子类实现
    public abstract ByteToMessageDecoder getDecoder();
    // 获取自定义编码器,由子类实现
    public abstract MessageToByteEncoder getEncoder();
    // 取客户端事件处理器,由子类实现
    public abstract ChannelInboundHandlerAdapter getClientHandler();
    @Override
    protected void initChannel(SocketChannel ch)  {
        //添加SSL安装验证
        SslHandler sslHandler = getSslHandler(ch);
        if(null != sslHandler) {
            ch.pipeline().addLast(sslHandler);
        }
        //添加心跳检测机制
        IdleStateHandler idleStateHandler = getIdleStateHandler();
        if(null != idleStateHandler) {
            ch.pipeline().addLast(idleStateHandler);
        }
        //添加自定义解码器
        ch.pipeline().addLast(getDecoder());
        //添加自定义编码器
        ch.pipeline().addLast(getEncoder());
        //添加业务处理器
        ch.pipeline().addLast(getClientHandler());
    }
}
